package com.yff.tuan.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yff.tuan.api.ApiResult;
import com.yff.tuan.api.Result;
import com.yff.tuan.model.Car;
import com.yff.tuan.model.CarExample;
import com.yff.tuan.model.CoFleet;
import com.yff.tuan.model.CoFleetExample;
import com.yff.tuan.model.CoPosition;
import com.yff.tuan.model.CoPositionExample;
import com.yff.tuan.model.CoRoleExample;
import com.yff.tuan.model.CoUser;
import com.yff.tuan.model.CoUserCar;
import com.yff.tuan.model.CoUserCarExample;
import com.yff.tuan.model.CoUserExample;
import com.yff.tuan.model.CoUserExample.Criteria;
import com.yff.tuan.model.UserCar;
import com.yff.tuan.service.CarService;
import com.yff.tuan.service.CoCompanyService;
import com.yff.tuan.service.CoFleetService;
import com.yff.tuan.service.CoUserService;
import com.yff.tuan.service.PositionService;
import com.yff.tuan.service.RoleService;
import com.yff.tuan.util.AESUtil;
import com.yff.tuan.util.StringUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired CarService carService;
	@Autowired CoUserService coUserService;
	@Autowired RoleService roleService;
	@Autowired PositionService positionService;
	@Autowired CoFleetService coFleetService;
	@Autowired CoCompanyService coCompanyService;
	
	@RequestMapping("/query")
	public String query(Model model,HttpServletRequest request,HttpServletResponse response) {
		int userId = (int) request.getSession().getAttribute("userId");
		CoUserExample example = new CoUserExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andParentIdEqualTo(userId);
		model.addAttribute("users", coUserService.query(example));
		return "/user";
	}
	
	@RequestMapping("/toadd")
	public String toadd(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		int userId = (int) request.getSession().getAttribute("userId");
		if(null != id){
			model.addAttribute("user", coUserService.findByPrimaryKey(id));
		}
		CoPositionExample positionExample = new CoPositionExample();
		positionExample.createCriteria().andUserIdEqualTo(userId);
		model.addAttribute("positions", positionService.query(positionExample));
		CoFleetExample coFleetExample=new CoFleetExample();
		coFleetExample.createCriteria().andCoUserIdEqualTo(userId);
		model.addAttribute("fleets", coFleetService.query(coFleetExample));
		return "user_add";
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public Object add(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		if(null == id) {
			return ApiResult.ERROR(Result.INVALID_PARAMETERS);
		}
		return ApiResult.SUCCESS(coUserService.delByPrimaryKey(id));
	}
	
	@RequestMapping("/password")
	@ResponseBody
	public Object password(Model model,String upassword,HttpServletRequest request,HttpServletResponse response){
		int userId = (int) request.getSession().getAttribute("userId");
		CoUser coUser = new CoUser();
		coUser.setId(userId);
		coUser.setPassword(AESUtil.Encrypt(upassword));
		return ApiResult.SUCCESS(coUserService.updateByPrimaryKeySelective(coUser));
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Object add(Model model,CoUser coUser,HttpServletRequest request,HttpServletResponse response){
		if(null == coUser) {
			return ApiResult.ERROR(Result.INVALID_PARAMETERS);
		}
		int userId = (int) request.getSession().getAttribute("userId");
		coUser.setParentId(userId);
		coUser.setPassword(StringUtil.isEmpty(coUser.getPassword())?AESUtil.Encrypt("123456"):AESUtil.Encrypt(coUser.getPassword()));
		coUser.setCreateDate(new Date());
		CoUser check = new CoUser();
		check.setName(coUser.getName());
		CoFleet fleet = coFleetService.findByPrimaryKey(coUser.getFleetId());
		if(null != fleet) {
			coUser.setCompanyId(fleet.getCompanyId());
		}
		if(null  != coUser.getId()){
			check.setId(coUser.getId());
			if(coUserService.exist(check)) {
				return ApiResult.ERROR(Result.ALREADY_EXIST_USER_NAME);
			}
			return ApiResult.SUCCESS(coUserService.updateByPrimaryKey(coUser));
		}else{
			if(coUserService.exist(check)) {
				return ApiResult.ERROR(Result.ALREADY_EXIST_USER_NAME);
			}
			return ApiResult.SUCCESS(coUserService.insert(coUser));
		}
	}
	
	@RequestMapping("/rights")
	public String rights(Model model,Integer id,HttpServletRequest request,HttpServletResponse response) {
		int userId = (int) request.getSession().getAttribute("userId");
		CoUser user = coUserService.findByPrimaryKey(id);
		if(null != user ) {
			if(null != user.getFleetId() ) {
				CoFleet fleet = coFleetService.findByPrimaryKey(user.getFleetId());
				if(null != fleet ) {
					user.setFleetName(fleet.getName());
				}
			}
			if(null != user.getPositionId() ) {
				CoPosition position = positionService.findByPrimaryKey(user.getPositionId());
				if(null != position ) {
					user.setPositionName(position.getName());
				}
			}
		}
		CarExample carExample = new CarExample();
		com.yff.tuan.model.CarExample.Criteria criteria = carExample.createCriteria();
		criteria.andCoUserIdEqualTo(userId);
		criteria.andFleetIdEqualTo(user.getFleetId());
		List<Car> cars = carService.query(carExample);
		CoUserCarExample example = new CoUserCarExample();
		example.createCriteria().andUserIdEqualTo(id);
		List<CoUserCar> userCars = coUserService.queryUserCar(example);
		if(null != cars && !cars.isEmpty()) {
			for(Car car:cars) {
				if(null != cars && !cars.isEmpty()) {
					for(CoUserCar userCar:userCars) {
						if(userCar.getCarId() == car.getId()) {
							car.setChecked(1);
							break;
						}
					}
				}
			}
		}
		model.addAttribute("cars", cars);
		model.addAttribute("user", user);
		return "/user_add_car";
	}
	
	@RequestMapping("/rightsSave")
	@ResponseBody
	public Object rightsSave(Model model,@RequestBody UserCar userCar,HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String,Object>();
		int userId = (int) request.getSession().getAttribute("userId");
		try {
			map.put("add", coUserService.saveUserCar(userCar));
		} catch (Exception e) {
			map.put("add",false);
		}
		return map;
	}
}
